package com.cykj.product.controller;

import com.cykj.common.core.domain.R;
import com.cykj.common.core.web.controller.BaseController;
import com.cykj.common.core.web.domain.AjaxResult;
import com.cykj.common.core.web.page.TableDataInfo;
import com.cykj.common.log.annotation.Log;
import com.cykj.common.log.enums.BusinessType;
import com.cykj.common.security.annotation.RequiresPermissions;
import com.cykj.product.domain.BsProductCategory;
import com.cykj.product.domain.BsProductInformation;
import com.cykj.product.service.BsProductInformationService;
import com.cykj.system.api.RemoteFileService;
import com.cykj.system.api.domain.SysFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/product")
public class BsProductInformationController extends BaseController {

    @Resource
    private RemoteFileService remoteFileService;

    @Autowired
    private BsProductInformationService productInformationService;
    @GetMapping("/list")
    public TableDataInfo getProductList(BsProductInformation bsProductInformation) {
        startPage();
        List<BsProductInformation> list = productInformationService.selectProductListWithCategory(bsProductInformation);
        return getDataTable(list);
    }
    /**
     * 获取商品信息详细信息
     */
    @RequiresPermissions("product:information:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(productInformationService.selectBsProductInformationById(id));
    }
    @GetMapping("/listByCategory")
    public AjaxResult listByCategory(@RequestParam(required = true) Long categoryId) {
        // 1. 校验参数（分类ID不能为空）
        if (categoryId == null || categoryId <= 0) {
            return AjaxResult.error("请选择有效的商品分类");
        }
        // 2. 构建查询条件（仅设置categoryId）
        BsProductInformation query = new BsProductInformation();
        query.setCategoryId(categoryId);  // 只传递分类ID，其他参数留空（由MyBatis自动忽略）
        query.setStatus(1);
        // 3. 调用服务查询
        List<BsProductInformation> productList = productInformationService.selectProductListWithCategory(query);
        return AjaxResult.success(productList);
    }
    // 单个商品下架
    @PutMapping("/takeOff/{id}")
    public AjaxResult takeOffProduct(@PathVariable Long id) {
        return toAjax(productInformationService.takeOffProduct(id));
    }

    // 批量商品下架
    @PutMapping("/batchTakeOff")
    public AjaxResult batchTakeOffProduct(@RequestBody List<Long> ids) {
        return toAjax(productInformationService.batchTakeOffProduct(ids));
    }
    /**
     * 新增商品信息
     */
    @RequiresPermissions("product:information:add")
    @Log(title = "商品信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestParam String productName,
                          @RequestParam Long categoryId,
                          @RequestParam Double price,
                          @RequestParam String description,
                          @RequestParam MultipartFile productImage,
                          @RequestParam Long status,
                          @RequestParam Long stock,
                          @RequestParam Long shopId
          ) {
        R<SysFile> productImageFile = remoteFileService.upload(productImage);

        String productImagePath = productImageFile.getData().getPath();

        String productImageUrl = productImageFile.getData().getUrl();

        BsProductInformation productInformation = new BsProductInformation();

        productInformation.setProductName(productName);
        productInformation.setCategoryId(categoryId);
        productInformation.setPrice(price);
        productInformation.setDescription(description);
        productInformation.setStatus(status);
        productInformation.setStock(stock);
        productInformation.setShopId(shopId);
        productInformation.setProductImage(productImageUrl);
        System.out.println(productInformation);
        return toAjax(productInformationService.insertBsProductInformation(productInformation));

    }

    /**
     * 修改商品信息
     */
    @RequiresPermissions("product:information:edit")
    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")

    public AjaxResult edit(
            @RequestParam Long id,
            @RequestParam String productName,
            @RequestParam Long categoryId,
            @RequestParam Double price,
            @RequestParam String description,
            @RequestParam(required = false) MultipartFile productImage,  // 图片可选
            @RequestParam Long status,
            @RequestParam Long stock,
            @RequestParam Long shopId
    ) {
        // 先查询原有商品信息
        BsProductInformation product = productInformationService.selectBsProductInformationById(id);
        if (product == null) {
            return AjaxResult.error("商品不存在");
        }

        // 如果有新图片，则上传并更新路径
        if (productImage != null && !productImage.isEmpty()) {
            R<SysFile> uploadResult = remoteFileService.upload(productImage);
            if (uploadResult.getCode() != 200 || uploadResult.getData() == null) {
                return AjaxResult.error("图片上传失败：" + uploadResult.getMsg());
            }
            product.setProductImage(uploadResult.getData().getUrl());
        }

        // 更新其他商品信息
        product.setProductName(productName);
        product.setCategoryId(categoryId);
        product.setPrice(price);
        product.setDescription(description);
        product.setStatus(status);
        product.setStock(stock);
        product.setShopId(shopId);

        return toAjax(productInformationService.updateBsProductInformation(product));


    }

    /**
     * 根据店铺ID查询商品分类
     */
    @GetMapping("/category/listByShop")
    public AjaxResult getCategoryByShopId(@RequestParam(required = true) Long shopId) {
        if (shopId == null || shopId <= 0) {
            return AjaxResult.error("无效的店铺ID");
        }
        List<BsProductCategory> categories = productInformationService.selectCategoryByShopId(shopId);
        return AjaxResult.success(categories);
    }
}